package com.letoken.platform.repo.wallet.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.letoken.platform.repo.wallet.dao.Web3ChainProviderMapper;
import com.letoken.platform.repo.wallet.po.Web3ChainProvider;
import com.letoken.platform.repo.wallet.redis.Web3ChainProviderRedis;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @author letokenlabs
 * @date 2022/11/18$
 */
@Log4j2
@Repository
public class Web3ChainProviderManager {

    @Autowired
    private Web3ChainProviderMapper web3ChainProviderMapper;

    public Web3ChainProvider getProvider(String netType){
        Web3ChainProvider provider = Web3ChainProviderRedis.me().getClassObject(netType);
        if (provider==null) {
            provider = queryByNetwork(netType);
            if (provider != null) {
                Web3ChainProviderRedis.me().put(netType, provider);
                return provider;
            }
        }
        return provider;
    }

    public boolean updateProvider(Web3ChainProvider provider){

        if (provider!=null) {
            web3ChainProviderMapper.updateById(provider);
            Web3ChainProviderRedis.me().put(provider.getNetwork(), provider);
        }
        return true;
    }
    
    public Web3ChainProvider queryByNetwork(String netType) {
        QueryWrapper<Web3ChainProvider> query = new QueryWrapper<>();
        query.eq("network", netType);
        return web3ChainProviderMapper.selectOne(query);
    }

}
